package com.linkoog.devtools.project_manager.settings;

import com.intellij.ide.GeneralLocalSettings;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.platform.ide.progress.ModalTaskOwner;
import com.intellij.platform.ide.progress.TaskCancellation;
import com.intellij.platform.ide.progress.TaskSupport;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import com.intellij.util.ui.table.TableModelEditor;
import com.linkoog.devtools.project_manager.settings.domain.ProjectDirectory;
import kotlinx.coroutines.CoroutineScope;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

public class ProjectManagerConfigurableUI {
    private JPanel myMainPanel;
    private final JBTable table;
    private final ListTableModel<ProjectDirectory> model;

    public ProjectManagerConfigurableUI() {
        final TreeSet<ProjectDirectory> projectDirectorys = ProjectManagerSetting.getInstance().getProjectDirectorys();
        if (projectDirectorys == null || projectDirectorys.isEmpty()){
            model = new ListTableModel<>(COLUMNS);
        } else {
            model = new ListTableModel<>(COLUMNS, new ArrayList<>(projectDirectorys));
        }

        table = new JBTable(model);
        final ToolbarDecorator toolbarDecorator = ToolbarDecorator.createDecorator(table);
        toolbarDecorator.disableUpDownActions();
        toolbarDecorator.setAddAction(button -> {
            //ApplicationManager.getApplication().invokeLater(this::chooseFile);

            DataContext dataContext = button.getDataContext();
            Project project = dataContext.getData(CommonDataKeys.PROJECT);
            chooseFile(project);
        });

        toolbarDecorator.setRemoveAction(button -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                model.removeRow(selectedRow);
            }
        });

        JPanel jPanel = toolbarDecorator.createPanel();
        myMainPanel.add(jPanel, BorderLayout.CENTER);
    }

    private void chooseFile(Project project) {
        VirtualFile toSelect = null;
        String defaultProjectDirectory = GeneralLocalSettings.getInstance().getDefaultProjectDirectory();
        if (isEmpty(defaultProjectDirectory)) {
            defaultProjectDirectory = System.getProperty("user.home");
        }
        toSelect = VfsUtil.findFileByIoFile(new File(defaultProjectDirectory), false);

        FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false);

        FileChooser.chooseFile(descriptor, project, myMainPanel, toSelect, virtualFile -> {
            TaskSupport taskSupport = ApplicationManager.getApplication().getService(TaskSupport.class);
            ModalTaskOwner owner = project == null? ModalTaskOwner.guess() : ModalTaskOwner.project(project);
            taskSupport.runWithModalProgressBlockingInternal(owner, "Open Prject", TaskCancellation.cancellable(), (coroutineScope, continuation) -> {
                return (CoroutineScope) () -> {
                    if (virtualFile != null && virtualFile.isValid() && virtualFile.getCanonicalPath() != null){
                        Path path  = virtualFile.toNioPath();
                        model.addRow(new ProjectDirectory(path.getFileName().toString(), virtualFile.getCanonicalPath()));
                    }
                    return continuation.getContext();
                };
            });


        });

    }

    public JPanel getMyMainPanel() {
        return myMainPanel;
    }


    public ListTableModel<ProjectDirectory> getModel(){
        return model;
    }

    public List<ProjectDirectory> getModelItems(){
        return model.getItems();
    }

    private static final ColumnInfo[] COLUMNS = {
            new TableModelEditor.EditableColumnInfo<ProjectDirectory, String>("名称") {
                @NotNull
                @Override
                public String valueOf(ProjectDirectory projectDirectory) {
                    return projectDirectory.getName();
                }

                @Override
                public void setValue(ProjectDirectory projectDirectory, String value) {
                    projectDirectory.setName(value);
                }

                @Override
                public boolean isCellEditable(ProjectDirectory projectDirectory) {
                    return false;
                }

            },
            new TableModelEditor.EditableColumnInfo<ProjectDirectory, String>("路径") {
                @NotNull
                @Override
                public String valueOf(ProjectDirectory projectDirectory) {
                    return projectDirectory.getPath();
                }

                @Override
                public void setValue(ProjectDirectory projectDirectory, String value) {
                    projectDirectory.setPath(value);
                }

                @Override
                public boolean isCellEditable(ProjectDirectory projectDirectory) {
                    return false;
                }
            }
    };


    public static boolean isEmpty(CharSequence str) {
        return str == null || str.length() == 0;
    }
}
